package com.yj.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.yj.AppJwtUtil;
import com.yj.Result.ResponseResult;
//import com.yj.ValidateCodeUtils;
import com.yj.apUser.pojo.ApUser;
import com.yj.Sample;
import com.yj.apUser.pojo.ApUserInfo;
import com.yj.mapper.ApUserInfoMapper;
import com.yj.service.ApUserService;
import com.yj.mapper.ApUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;
import java.util.concurrent.TimeUnit;

/**
* @author 86132
* @description 针对表【ap_user(用户主表)】的数据库操作Service实现
* @createDate 2025-02-18 14:07:38
*/
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser>
    implements ApUserService {
    @Resource
    private ApUserMapper apUserMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApUserInfoMapper apUserInfoMapper;


    //app用户注册
    @Override
    public ResponseResult register(Map<String,Object> map) {
        String nickname = (String) map.get("nickname");
        String phone = (String) map.get("phone");
        String birthdatex = (String) map.get("birthdate");
        //将 gender 转换为 Integer 类型
        String genderStr = (String) map.get("gender");
        Integer gender = null;
        try {
            if (genderStr != null && !genderStr.isEmpty()) {
                gender = Integer.valueOf(genderStr); // 将 String 转为 Integer
            }
        } catch (NumberFormatException e) {
            return ResponseResult.errorResult(400, "性别格式不正确!");
        }
        //参数校验 不信任原则
        if (StringUtils.isBlank(nickname) || nickname.isEmpty()) {
            return ResponseResult.errorResult(400, "昵称不能为空!");
        }
        if (StringUtils.isBlank(phone) || phone.isEmpty()) {
            return ResponseResult.errorResult(400, "电话不能为空!");
        }
        if(CheckPhone(phone)){
            log.trace("有效的电话号码：" + phone);
        }else {
            return ResponseResult.errorResult(400, "手机号格式不正确!");
        }
        if (gender == null || (gender != 1 && gender != 0)) { //1男 0女
            return ResponseResult.errorResult(400, "性别不能为空!");
        }
        if (StringUtils.isBlank(birthdatex) || birthdatex.isEmpty()) {
            return ResponseResult.errorResult(400, "出生日期不能为空!");
        }
        //注册用户
        ApUser apUser = new ApUser();
        apUser.setNickName(nickname);
        apUser.setPhone(phone);
        apUser.setAvatarUrl(null);
        apUserMapper.insert(apUser);
        //获取新用户id
        Integer id = apUser.getId();

        //性别 生日 添加到用户详细信息userinfo
        ApUserInfo apUserInfo = new ApUserInfo();
        apUserInfo.setUserId(id);
        apUserInfo.setGender(gender);
        //日期格式化
        Date birthdate = convertStringToDate(birthdatex);
        apUserInfo.setBirthdate(birthdate);
        apUserInfoMapper.insert(apUserInfo);

        return ResponseResult.okResult(200, "注册成功!");
    }

    //日期格式化
    public static Date convertStringToDate(String dateString) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(dateString); // 将字符串转换为日期
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    //电话位数校验
    public static boolean CheckPhone(String phone) {
        // 校验手机号长度是否为 11 位，并且是否为纯数字
        if (phone != null && phone.length() == 11 && phone.matches("\\d+")) {
            return true;
        }
        return false;
    }


    /**
     * 实现 用户端手机号验证码登录功能
     * 参数 LoginDto 手机号 phone 接收验证码
     */
    @Override
    @Transactional // 确保整个方法在一个事务中执行
    public ResponseResult loginByPhone(ApUser user, HttpSession httpSession) {
        // 检查手机号是否为空
        if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
            return ResponseResult.errorResult(501, "手机号不能为空");
        }

        // 获取手机号和验证码
        String phone = user.getPhone();
        String code = user.getCode();

        // 从Redis获取存储的验证码
        String sessionCode = redisTemplate.opsForValue().get(phone);
        System.out.println("Redis中的验证码: " + sessionCode);

        // 验证码比对
        if (sessionCode == null || !code.equals(sessionCode)) {
            return ResponseResult.errorResult(501, "验证码错误或已过期");
        }

        // 查询用户是否存在
        LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUser::getPhone, phone);
        ApUser tUser = apUserMapper.selectOne(queryWrapper);

        if (tUser == null) {
//            // 如果是新用户，则注册
//            TUser newUser = new TUser();
//            newUser.setPhone(phone);
//            newUser.setStatus(1); // 假设1表示正常状态
//            tUserMapper.insert(newUser);
//            tUser = newUser;
            return ResponseResult.errorResult(501, "用户不存在");
        }

        // 设置会话属性
        httpSession.setAttribute("user", tUser.getId());

        // 生成并返回登录结果
//        String token = AppJwtUtil.getToken(tUser.getId().longValue());
        Map<String, Object> map = new HashMap<>();
        map.put("uid", tUser.getId());
//        map.put("token", token);

        return ResponseResult.okResult(map);
    }

    /**
     * 发送验证码
     * @param apUser
     * @param httpSession
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult sendMsg(ApUser apUser, HttpSession httpSession) throws Exception {
//获取手机号
        String phone = apUser.getPhone();
        if (phone != null) {
            //生成验证码
//            String code = ValidateCodeUtils.generateValidateCode(4).toString();
//            System.out.println(code);
            //调用阿里云API发送短信
//            Sample.show("我爱学习", "SMS_476550315", phone, code);
            //将生成的验证码保存到Session中
//            httpSession.setAttribute(phone, code);
            //将生成的验证码保存到redis中
//            redisTemplate.opsForValue().set(phone,code);
            // 设置验证码内容和过期时间（例如 1 分钟)
            redisTemplate.expire(phone, 1 , TimeUnit.MINUTES);
            return ResponseResult.okResult("短信发送成功");
        }
        return ResponseResult.errorResult( 501,"短信发送失败");
    }

}






